package eventHandling.fileHandling;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.nio.file.Files;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Element;
import org.w3c.dom.Document;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import org.apache.commons.codec.binary.Base64;

/**
 * The class handles click on Load file button in the application window
 * @author Martin
 */
public class FileLoadHandler implements ActionListener{
    private JSVGCanvas _svgCanvas;
    private JPanel _jpanel;
    private JFrame _mainFrame;
    
    /**
     * 
     * @param canvas the SVG canvas we are hadling the event for
     * @param panel panel around the svg canvas
     * @param mainFrame the whole application window
     */
    public FileLoadHandler(JSVGCanvas canvas, JPanel panel, JFrame mainFrame)
    {
        _svgCanvas = canvas;
        _jpanel = panel;
        _mainFrame = mainFrame;
    }
    
    /**
     * Querry for user to choose the file to open. 
     * With Files.probeContentType() (JDK 1.7) get mime type of file.
     * 
     * If mime type is image/bmp, then convert it to png, save it to
     * ByteArrayOutputStream and then encode id to base64.
     * SVG document will be created, height and width will be set same as
     * height and width from image, then element image will be crated. 
     * To that element will be embedded original image by xlink:href data 
     * base64. At the end, the document will be set in _svgCanvas to created 
     * SVG document.
     * 
     * If mime type is not image/bmp, then is assumed, that choosen file is SVG
     * and the method will try to import it right in _svgCanvas 
     * by (svgCanvas.setUri())
     * 
     * @ param ae
     */
    @Override
    public void actionPerformed(ActionEvent ae) {
        //enable the possibility to resize application window
        //this option is disabled when this method ends
        //to prevent user from changing the size thus breaking the coordinates
        _mainFrame.setResizable(true);

        //use JFileChooser class to select file to give to SVGCanvas to load
        JFileChooser fc = new JFileChooser(".");
        int choice = fc.showOpenDialog(_jpanel);
        if (choice == JFileChooser.APPROVE_OPTION) {
            try {
                File selectedFile = fc.getSelectedFile();
                String mimeType = Files.probeContentType(selectedFile.toPath());
                if (mimeType.equals("image/bmp") || mimeType.equals("image/jpeg") || mimeType.equals("image/png")) {
                    BufferedImage img = ImageIO.read(selectedFile);
                    ByteArrayOutputStream pngStream = new ByteArrayOutputStream();
                    ImageIO.write(img, "png", pngStream);
                    String imgBase64 = Base64.encodeBase64String(pngStream.toByteArray());

                    DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
                    String ns = SVGDOMImplementation.SVG_NAMESPACE_URI;
                    Document svg = impl.createDocument(ns, "svg", null);
                    
                    Element svgRoot = svg.getDocumentElement();
                    svgRoot.setAttributeNS(null, "width", Integer.toString(img.getWidth()));
                    svgRoot.setAttributeNS(null, "height", Integer.toString(img.getHeight()));

                    Element svgImage = svg.createElementNS(ns, "image");
                    svgImage.setAttributeNS(null, "x", "0");
                    svgImage.setAttributeNS(null, "y", "0");
                    svgImage.setAttributeNS(null, "width", Integer.toString(img.getWidth()));
                    svgImage.setAttributeNS(null, "height", Integer.toString(img.getHeight()));
                    svgImage.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "data:image/png;base64,"+imgBase64);
                    
                    svgRoot.appendChild(svgImage);
                    
                    _svgCanvas.setDocument(svg);
                } else { // image/svg+xml
                    _svgCanvas.setURI(selectedFile.toURI().toString());
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        
        _mainFrame.setResizable(false);
    }
}

